package ldh.maker.freemaker;

import ldh.database.Column;
import ldh.database.Table;
import ldh.maker.database.TableInfo;
import ldh.maker.util.FreeMakerUtil;
import ldh.maker.vo.TableViewData;

import java.util.ArrayList;
import java.util.List;

public class JspMaker extends FreeMarkerMaker<JspMaker> {
	
	private Table table;
	private String ftl;
	private List<Column> columns = new ArrayList<Column>();
	private TableInfo tableInfo;
	private boolean isShiro = false;
	
	public JspMaker table(Table table) {
		this.table = table;
		TableViewData tableViewData = tableInfo.getTableViewDataMap().get(table.getName());
		List<TableViewData.ColumnData> columnDatas = tableViewData.getColumnDatas();
		for (Column c : table.getColumnList()) {
			boolean isHave = false;
			for (TableViewData.ColumnData columnData : columnDatas) {
				if (columnData.getColumnName().equals(c.getName())) {
					isHave = true;
					c.setCreate(columnData.getShow());
					c.setWidth(columnData.getWidth());
				}
			}
			if (!isHave) continue;
			if (FreeMakerUtil.isDate(c)) {
				Column cc = new Column(c.getName(), "开始" + FreeMakerUtil.comment(c), c.getType());
				cc.setProperty("start" + FreeMakerUtil.firstUpper(c.getProperty()));
				Column cc2 = new Column(c.getName(), "结束" + FreeMakerUtil.comment(c), c.getType());
				cc2.setProperty("end" + FreeMakerUtil.firstUpper(c.getProperty()));
				columns.add(cc);
				columns.add(cc2);
			} else {
				columns.add(c);
			}
		}
		return this;
	}
	
	public JspMaker ftl(String ftl) {
		this.ftl = ftl;
		return this;
	}

	public JspMaker shiro(boolean isShiro) {
		this.isShiro = isShiro;
		return this;
	}

	public JspMaker tableInfo(TableInfo tableInfo) {
		this.tableInfo = tableInfo;
		return this;
	}
	
	public JspMaker make() {
		data();
		out(ftl, data);
		
		return this;
	}
	
	public void data() {
		check();
		data.put("table", table);
		data.put("columns", columns);
		data.put("tableInfo", tableInfo);
		data.put("shiro", isShiro);
//		data.put("module", MakerConfig.getInstance().getParam().getModule());
	}
	
	protected void check() {
		if (table == null) {
			throw new NullPointerException("table must not be null");
		}
		if (ftl == null) {
			throw new NullPointerException("ftl must not be null");
		}
		super.check();
		
	}

}
